package com.caipin.controller;

import com.caipin.domain.camera.CourseInfo;
import com.caipin.domain.camera.StudentPhotoInfos;
import com.caipin.domain.web.ResultJson;
import com.caipin.service.CameraPlatformManagementService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Author: zhunian0322@163.com
 * @DateTime: 2020-08-02 9:46
 * @Description: TODO
 */
@RestController
@RequestMapping({"/cameraPlatformManagement"})
public class CameraPlatformManagementController {
    private static final Logger log = LoggerFactory.getLogger(com.caipin.controller.CameraPlatformManagementController.class);

    @Autowired
    private CameraPlatformManagementService cameraPlatformManagementService;

    @Autowired
    private ObjectMapper objectMapper;

    @PostMapping({"/setPedestrianThreshold"})
    public Object setPedestrianThreshold(@RequestBody Map<String, Object> map) {
        Integer i = (Integer)map.get("pedestrianThreshold");
        if (i == null)
            return ResultJson.failure(ResultCode.BAD_REQUEST);
        this.cameraPlatformManagementService.updatePedestrianThreshold(i);
        return ResultJson.ok();
    }

    @GetMapping({"/getPedestrianThreshold"})
    public Object getPedestrianThreshold() {
        int i = this.cameraPlatformManagementService.getPedestrianThreshold();
        return ResultJson.ok(Integer.valueOf(i));
    }

    @GetMapping({"/studentPhoto/{grade}/{clbum}"})
    public Object getStudentPhoto(@PathVariable("grade") String grade, @PathVariable("clbum") String clbum) {
        StudentPhotoInfos studentPhotoInfos = this.cameraPlatformManagementService.getStudentPhotoInfos(grade, clbum);
        return ResultJson.ok(studentPhotoInfos);
    }

    @GetMapping({"/studentPhotoById/{studentId}"})
    public Object getStudentPhotoByStudentId(@PathVariable("studentId") String studentId) {
        String studentPhotoBase64 = this.cameraPlatformManagementService.getStudentPhoto(studentId);
        return ResultJson.ok(studentPhotoBase64);
    }

    @GetMapping({"/courseTable/{classroomId}"})
    public Object getCourseTable(@PathVariable("classroomId") String classroomId) {
        CourseInfo courseInfo = this.cameraPlatformManagementService.getCourseTableInfos(classroomId);
        return ResultJson.ok(courseInfo);
    }

    @GetMapping({"/studentIdList/{classId}"})
    public Object getStudentIdList(@PathVariable("classId") String classId) {
        List<String> studentIdList = this.cameraPlatformManagementService.getStudentIdList(classId);
        if (studentIdList == null)
            return ResultJson.failure(ResultCode.BAD_REQUEST);
        return ResultJson.ok(studentIdList);
    }

    @PostMapping({"/analysisResult"})
    public Object updateAnalysisResult(@RequestBody CourseEvent courseEvent) {
        this.cameraPlatformManagementService.saveCourseEvent(courseEvent);
        return ResultJson.ok();
    }

    @PostMapping({"/analysisResultStatisticalRate"})
    public Object updateAnalysisResultStatisticalRate(@RequestBody AnalysisResultRate analysisResultRate) {
        log.info(analysisResultRate.toString());
        this.cameraPlatformManagementService.saveAnalysisResultStatisticalRate(analysisResultRate);
        return ResultJson.ok();
    }

    @PostMapping({"/security/analysisResult"})
    public Object updateSecurityAnalysisResult(@RequestParam("image") MultipartFile file, @RequestParam("json_info") String jsonInfo) {
        try {
            byte[] bytes = file.getBytes();
            String imageBase64 = Base64.getEncoder().encodeToString(bytes);
            SecurityEvent securityEvent = (SecurityEvent)this.objectMapper.readValue(jsonInfo, SecurityEvent.class);
            SecurityWarning securityWarning = (new SecurityWarning()).setMark(Boolean.valueOf(false)).setAddress(securityEvent.getChannelLocation());
            for (SecurityEvent.ObjectsBean object : securityEvent.getObjects()) {
                if (object.getType().equals("CAR_PLATE")) {
                    long imageId = this.cameraPlatformManagementService.saveSecurityEventImage(securityEvent, imageBase64);
                    SecurityCar securityCar = (new SecurityCar()).setImageId(Long.valueOf(imageId)).setDeviceId(securityEvent.getDeviceId()).setChannelId(Integer.valueOf(securityEvent.getChannelId())).setSnapTime(securityEvent.getSnapTime()).setType(object.getType()).setBboxX(Integer.valueOf(object.getBbox().getX())).setBboxY(Integer.valueOf(object.getBbox().getY())).setBboxHeight(Integer.valueOf(object.getBbox().getHeight())).setBboxWidth(Integer.valueOf(object.getBbox().getWidth())).setProbability(Double.valueOf(object.getProbability())).setCarLicenceNumber(object.getCarLicenceNumber());
                    if (object.getAlarmInfo() != null)
                        securityCar.setAlarmInfoType(object.getAlarmInfo().getListType())
                                .setAlarmInfoName(object.getAlarmInfo().getListName());
                    this.cameraPlatformManagementService.saveSecurityEventCar(securityCar);
                    continue;
                }
                if (object.getType().equals("PEDESTRIAN")) {
                    if (object.getCount().intValue() < this.cameraPlatformManagementService.getPedestrianThreshold()) {
                        log.info("+ object.getCount() + "]+ this.cameraPlatformManagementService.getPedestrianThreshold() + ");
                        return ResultJson.ok();
                    }
                    long imageId = this.cameraPlatformManagementService.saveSecurityEventImage(securityEvent, imageBase64);
                    SecurityPedestrian securityPedestrian = (new SecurityPedestrian()).setImageId(Long.valueOf(imageId)).setDeviceId(securityEvent.getDeviceId()).setChannelId(Integer.valueOf(securityEvent.getChannelId())).setSnapTime(securityEvent.getSnapTime()).setType(object.getType()).setBboxX(Integer.valueOf(object.getBbox().getX())).setBboxY(Integer.valueOf(object.getBbox().getY())).setBboxHeight(Integer.valueOf(object.getBbox().getHeight())).setBboxWidth(Integer.valueOf(object.getBbox().getWidth())).setMark(Boolean.valueOf(false)).setCount(object.getCount());
                    this.cameraPlatformManagementService.saveSecurityPedestrian(securityPedestrian);
                    securityWarning.setEvent("+ object.getCount() + ");
                    continue;
                }
                if (object.getType().equals("FACE_SNAP")) {
                    long imageId = this.cameraPlatformManagementService.saveSecurityEventImage(securityEvent, imageBase64);
                    SecurityFace securityFace = (new SecurityFace()).setImageId(Long.valueOf(imageId)).setDeviceId(securityEvent.getDeviceId()).setChannelId(Integer.valueOf(securityEvent.getChannelId())).setSnapTime(securityEvent.getSnapTime()).setChip(object.getChip()).setType(object.getType()).setBboxX(Integer.valueOf(object.getBbox().getX())).setBboxY(Integer.valueOf(object.getBbox().getY())).setBboxWidth(Integer.valueOf(object.getBbox().getWidth())).setBboxHeight(Integer.valueOf(object.getBbox().getHeight())).setProbability(Double.valueOf(object.getProbability())).setFeatureBin(object.getFeatureBin()).setFaceStranger(Boolean.valueOf(true)).setMark(Boolean.valueOf(false));
                    if (object.getAlarmInfo() != null)
                        securityFace.setAlarmInfoType(object.getAlarmInfo().getListType())
                                .setAlarmInfoName(object.getAlarmInfo().getListName());
                    if (object.getRecognization() != null) {
                        StringBuilder sb = new StringBuilder();
                        for (String s : object.getRecognization().getList())
                            sb.append(s).append(",");
                        sb.deleteCharAt(sb.lastIndexOf(","));
                        securityFace.setUserId(object.getRecognization().getPersonInfo().getId())
                                .setUsername(object.getRecognization().getPersonInfo().getName())
                                .setUserImageId(Integer.valueOf(((SecurityEvent.ObjectsBean.RecognizationBean.PersonInfoBean.ImagesBean)object.getRecognization().getPersonInfo().getImages().get(0)).getImageId()))
                                .setImageBase64(((SecurityEvent.ObjectsBean.RecognizationBean.PersonInfoBean.ImagesBean)object.getRecognization().getPersonInfo().getImages().get(0)).getData())
                                .setCitizenId(object.getRecognization().getPersonInfo().getCitizenId())
                                .setEmployeeId(object.getRecognization().getPersonInfo().getEmployeeId())
                                .setCreatedTime(object.getRecognization().getPersonInfo().getCreatedAt())
                                .setRosterList(sb.toString())
                                .setFaceStranger(Boolean.valueOf(false));
                    }
                    this.cameraPlatformManagementService.saveSecurityEventFace(securityFace);
                    securityWarning.setEvent(");
                }
            }
            this.cameraPlatformManagementService.saveSecurityWarning(securityWarning);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultJson.ok();
    }

    @PostMapping({"/invasionReport"})
    Object invasionReport(@RequestBody InvasionReport invasionReport) {
        try {
            String classroomId = invasionReport.getClassroomId();
            System.out.println("classroomId:" + classroomId);
            String happenTime = invasionReport.getHappenTime();
            System.out.println("happenTime:" + happenTime);
            String base64 = invasionReport.getImg().getBase64();
            System.out.println("base64:" + base64);
            byte[] decode = Base64.getDecoder().decode(base64);
            FileOutputStream fileOutputStream = FileUtils.openOutputStream(new File("Users/zhunian/Desktop/suntest", UUID.randomUUID().toString() + ".jpg"));
            fileOutputStream.write(decode);
            fileOutputStream.flush();
            fileOutputStream.close();
            this.cameraPlatformManagementService.saveInvasionReport(invasionReport);
            return ResultJson.ok();
        } catch (Throwable $ex) {
            throw $ex;
        }
    }
}

